# -*- coding: utf-8 -*-

import os
import requests
import wget
import hashlib
import tarfile

def has_new_ver(ver_fname,ver_url):

    #如果本地没有版本文件,则有新版本
    if not os.path.exists(ver_fname):
        return True

    #如果本地版本号与网上版本号不一样,则有新版本
    with open(ver_fname) as fg:
        local_ver = fg.read()

    r = requests.get(ver_url)
    if local_ver != r.text:
        return True
    else:
        return False

def file_ok(md5_url,app_fname):
    #检查文件是否完好
    m = hashlib.md5()
    with open(app_fname,'rb') as fg:
        while 1:
            data = fg.read(4096)
            if not data:
                break
            m.update(data)

    #比较网上的md5值
    r = requests.get(md5_url)
    if m.hexdigest() == r.text.strip():
        return True
    else:
        return False


def deploy(app_fname,deploy_dir,dest):
    #解压缩
    tar = tarfile.open(app_fname)
    tar.extractall(path=deploy_dir)
    tar.close()

    #拼接解压文件
    app_dir = os.path.basename(app_fname).replace('.tar.gz','')
    app_dir = os.path.join(deploy_dir,app_dir)
    #print(app_dir)

    #目标软连接存在,则删除
    if os.path.exists(dest):
        os.remove(dest)

    #创建连接文件
    os.symlink(app_dir,dest)


if __name__ == '__main__':
    ver_fname = '/var/www/deploy/live_ver'
    ver_url = 'http://139.9.84.12/deploy/live_ver'
    #检查是否有新版本
    if not has_new_ver(ver_fname,ver_url):
        print('未发现新版本!')
        exit(1)

    #下载新版本压缩包
    down_dir = '/var/www/download'
    r = requests.get(ver_url)
    app_url = 'http://139.9.84.12/deploy/pkgs/myweb-%s.tar.gz'%r.text
    wget.download(app_url,down_dir)

    #校验下载的压缩包是否损坏,如果损坏则删除
    md5_url = app_url+'.md5'
    app_fname = app_url.split('/')[-1]
    app_fname = os.path.join(down_dir,app_fname)
    if not file_ok(md5_url,app_fname):
        print('文件已损坏')
        os.remove(app_fname)
        exit(2)

    #部署软件
    deploy_dir = '/var/www/deploy'
    dest = '/var/www/html/nsd1909'
    deploy(app_fname,deploy_dir,dest)

    #更新本地文件
    if os.path.exists(ver_fname):
        os.remove(ver_fname)

    wget.download(ver_url,ver_fname)
    print('上线完成')